package com.example.workflow.controller;

import org.flowable.engine.RepositoryService;
import org.flowable.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;

@RestController
@RequestMapping("/process")
@Slf4j
public class ProcessViewController {

    @Autowired
    private RepositoryService repositoryService;

    @GetMapping(value = "/diagram/{processDefinitionId}")
    public void getProcessDiagram(@PathVariable String processDefinitionId, HttpServletResponse response) {
        try {
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery()
                    .processDefinitionId(processDefinitionId)
                    .singleResult();
            
            if (processDefinition != null) {
                String resourceName = processDefinition.getDiagramResourceName();
                if (resourceName == null) {
                    resourceName = processDefinition.getResourceName();
                }
                
                InputStream resourceAsStream = repositoryService.getResourceAsStream(
                        processDefinition.getDeploymentId(),
                        resourceName);

                if (resourceAsStream != null) {
                    byte[] b = new byte[1024];
                    int len;
                    response.setContentType("image/png");
                    OutputStream out = response.getOutputStream();
                    while ((len = resourceAsStream.read(b, 0, 1024)) != -1) {
                        out.write(b, 0, len);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} 